<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>08地图事件</title>
    <!-- 1.导入依赖 -->
    <link rel="stylesheet" href="https://lib.baomitu.com/ol3/4.6.5/ol.css" />
    <script src="https://lib.baomitu.com/ol3/4.6.5/ol.js"></script>
    <!-- 样式 -->
    <style>
      .btn {
        position: fixed;
        z-index: index 100;
        top: 30px;
        right: 30px;
      }
    </style>
  </head>
  <body>
    <!-- 2.设置地图容器的挂载点 -->
    <div id="map"></div>
    <!-- 按钮 -->
    <button class="btn">复位地图</button>
    <script>
      // 3.初始化一个高德图层(初始化地图)
      const gaode = new ol.layer.Tile({
        title: '高德地图',
        source: new ol.source.XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
          wrapX: false,
        }),
      })

      // 4.初始化openlayer地图
      const map = new ol.Map({
        // 将初始化的地图设置到id为map的DOM元素上
        target: 'map',
        layers: [gaode],
        view: new ol.View({
          center: [113.73, 33.62],
          // 设置地图的放大级别
          zoom: 5,
          projection: 'EPSG:4326',
        }),
      })
      // ---------------08地图事件--------------

      // source-layer
      var source = new ol.source.Vector({})
      var layer = new ol.layer.Vector({
        source,
      })
      map.addLayer(layer)
      // 给地图绑定一个点击事件
      map.on('click', (evt) => {
        // console.log('evt:', evt)
        // 解构
        var { coordinate } = evt
        var point = new ol.Feature({
          geometry: new ol.geom.Point(coordinate),
        })
        source.addFeature(point)

        // 实现飞行视角-漫游
        const view = map.getView()
        view.animate({
          center: coordinate,
        })
      })

      // 复位地图button功能
      var btn = document.querySelector('.btn')
      btn.onclick = function () {
        map.getView().animate({
          center: [113.73, 33.62],
          zoom: 5,
          duration: 2000,
        })
      }
    </script>
  </body>
</html>
